/*
 * @Author: huangtianyang 916072572@qq.com
 * @Date: 2023-11-22 16:19:19
 * @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @LastEditTime: 2024-06-03 11:06:41
 * @FilePath: \cxl-driving-training\src\views\channel\list\index.ts
 */
import { BaseData, BaseMethod } from '@/utils/basc-data'
import { tableConfig } from './config'
import { reactive } from 'vue'
import { ElMessage, FormInstance } from 'element-plus'
import {
    channelAdd,
    channelById,
    channelDelete,
    channelDisable,
    channelEdit,
    channelOperationInterface,
    channelPage,
    channelPageInterface,
    channelPromotionUrl
} from '@/apis/channel'
import { getDaysBetweenDates } from '@/utils'
import { optionsInterface } from '@/utils/dict-data'

export default class ChannelListData extends BaseData implements BaseMethod {
    dialog = reactive({
        visible: false,
        title: '新增渠道',
        width: '800px',
        type: 'create'
    })
    dialogForm = reactive({
        channel: '',
        deliveryType: '',
        url: '',
        time: '',
        otherTime: '',
        remark: '',
        id: ''
    })
    rules = {
        channel: [{ required: true, message: '请选择渠道', trigger: 'change' }],
        deliveryType: [{ required: true, message: '请选择投放类型', trigger: 'change' }],
        url: [{ required: true, message: '请输入渠道地址', trigger: 'blur' }],
        time: [{ required: true, message: '请输入投放期限', trigger: 'blur' }]
    }
    channelNameOptions = reactive<optionsInterface[]>([
        { value: '1', label: '微信公众号' },
        { value: '2', label: '抖音小程序' }
    ])
    deliveryTypeOptions = reactive<optionsInterface[]>([
        { value: '1', label: '线上' },
        { value: '2', label: '线下' }
    ])
    timeOptions = reactive<optionsInterface[]>([
        { value: '0', label: '长期' },
        { value: '1', label: '90天' },
        { value: '2', label: '其它' }
    ])
    searchData = {
        channelType: '',
        status: ''
    }

    constructor() {
        super(tableConfig)
        this.getData()
    }
    getData = (arg?: any) => {
        const params: channelPageInterface = {
            current: this.pageData.pagination.pageNo,
            size: this.pageData.pagination.pageSize
        }
        if (this.searchData.channelType !== '' && this.searchData.channelType !== '-1') {
            params.channelType = Number(this.searchData.channelType)
        }
        if (this.searchData.status !== '' && this.searchData.status !== '-1') {
            params.disable = Number(this.searchData.status)
        }
        channelPage(params).then(res => {
            if (Number(res.data.code) === 200) {
                this.pageData.table.data.length = 0
                this.pageData.pagination.total = res.data.result.total

                const arr: any[] = res.data.result.records

                arr.forEach((element: any) => {
                    element.status = Number(element.disable) === 0 ? true : false
                    element.name = this.channelNameOptions[Number(element.channelType) - 1].label
                    element.type = this.deliveryTypeOptions[Number(element.deliveryType) - 1].label
                    element.time = element.deliveryStartDate
                        ? getDaysBetweenDates(element.deliveryStartDate, element.deliveryEndDate)
                        : null
                    this.pageData.table.data.push(element)
                })
            }
        })
    }
    onSearch = (arg?: any) => {
        console.log(arg)
        this.searchData = arg
        this.getData()
    }
    onReset = (arg?: any) => {
        this.searchData = {
            channelType: '',
            status: ''
        }
        this.getData()
    }
    onPaginationChange = (arg?: any) => {
        this.pageData.pagination.pageNo = arg
        this.getData()
    }
    onPaginationSize = (arg?: any) => {
        this.pageData.pagination.pageNo = 1
        this.pageData.pagination.pageSize = arg
        this.getData()
    }
    //获取推广渠道url
    onGetPromotionUrl = () => {
        channelPromotionUrl().then(res => {
            if (Number(res.data.code) === 200) {
                const id = res.data.result.split('=')[1]
                this.dialogForm.id = id
                this.dialogForm.url = id
            }
        })
    }
    onOperation = (arg?: any) => {
        const { type, data } = arg
        console.log(type, data)
        if (type === 'create') {
            this.dialog.visible = true
            this.dialog.type = type
            this.dialog.title = '新增渠道'
            this.dialogForm.channel = ''
            this.dialogForm.deliveryType = ''
            this.dialogForm.url = ''
            this.dialogForm.time = ''
            this.dialogForm.otherTime = ''
            this.dialogForm.remark = ''
            this.dialogForm.id = ''
        } else if (type === 'edit') {
            this.dialog.type = type
            this.dialog.title = '编辑渠道'
            this.dialogForm.id = data.id
            channelById(data.id).then(res => {
                if (Number(res.data.code) === 200) {
                    this.dialog.visible = true
                    this.dialogForm.channel = res.data.result.channelType + ''
                    this.dialogForm.deliveryType = res.data.result.deliveryType + ''
                    this.dialogForm.url = res.data.result.id + ''
                    if (res.data.result.deliveryEndDate) {
                        const n = getDaysBetweenDates(
                            res.data.result.deliveryStartDate,
                            res.data.result.deliveryEndDate
                        )
                        if (n === 90) {
                            this.dialogForm.time = '1'
                        } else {
                            this.dialogForm.time = '2'
                            this.dialogForm.otherTime = n + ''
                        }
                    } else {
                        this.dialogForm.time = '0'
                    }

                    this.dialogForm.remark = res.data.result.remark
                    this.dialogForm.id = res.data.result.id + ''
                }
            })
        } else if (type === 'delete') {
            channelDelete(data.id).then(res => {
                if (Number(res.data.code) === 200) {
                    ElMessage.success('删除成功！')
                    this.getData()
                }
            })
        } else if (type === 'switch') {
            channelDisable(data.id, data.status ? 0 : 1).then(res => {
                if (Number(res.data.code) === 200) {
                    ElMessage.success('修改成功！')
                    // this.getData()
                } else {
                    data.status = !data.status
                }
            })
        }
    }

    setDay(n: number): { start: string; end: string } {
        const totay = new Date()
        const endDate = new Date(totay.getFullYear(), totay.getMonth(), totay.getDate() + n - 1)
        console.log({
            year: endDate.getFullYear(),
            month: endDate.getMonth() + 1,
            date: endDate.getDate()
        })
        const sm = totay.getMonth() + 1 < 10 ? '0' + (totay.getMonth() + 1) : totay.getMonth() + 1
        const em = endDate.getMonth() + 1 < 10 ? '0' + (endDate.getMonth() + 1) : endDate.getMonth() + 1

        const sd = totay.getDate() < 10 ? '0' + totay.getDate() : totay.getDate()
        const ed = endDate.getDate() < 10 ? '0' + endDate.getDate() : endDate.getDate()
        return {
            start: totay.getFullYear() + '-' + sm + '-' + sd + ' 00:00:00',
            end: endDate.getFullYear() + '-' + em + '-' + ed + ' 23:59:59'
        }
    }
    //监听弹窗关闭
    onCloseDialog = (formEl: FormInstance | undefined) => {
        if (!formEl) return
        formEl.resetFields()
        this.dialog.visible = false
    }
    //监听弹窗点击确定按钮
    submitForm = async (formEl: FormInstance | undefined) => {
        if (!formEl) return
        await formEl.validate((valid, fields) => {
            if (valid) {
                console.log('submit!', this.dialogForm)
                const data: channelOperationInterface = {
                    channelType: Number(this.dialogForm.channel),
                    deliveryType: Number(this.dialogForm.deliveryType),
                    deliveryEndDate: '',
                    deliveryStartDate: '',
                    id: this.dialogForm.id,
                    remark: this.dialogForm.remark
                }
                if (Number(this.dialogForm.time) === 0) {
                    data.deliveryEndDate = null
                    data.deliveryStartDate = null
                } else {
                    const day: { start: string; end: string } = this.setDay(
                        Number(this.dialogForm.time) === 1 ? 90 : Number(this.dialogForm.otherTime)
                    )
                    data.deliveryStartDate = day.start
                    data.deliveryEndDate = day.end
                }
                console.log('data', data)
                if (this.dialog.type === 'create') {
                    channelAdd(data).then(res => {
                        if (Number(res.data.code) === 200) {
                            ElMessage.success('新增成功！')
                            this.dialog.visible = false
                            this.getData()
                        }
                    })
                } else if (this.dialog.type === 'edit') {
                    data.id = this.dialogForm.id
                    channelEdit(data).then(res => {
                        if (Number(res.data.code) === 200) {
                            ElMessage.success('修改成功！')
                            this.dialog.visible = false
                            this.getData()
                        }
                    })
                }
            }
        })
    }
}
